<template>
	<view class="release_dynamics safe_area">
		<u-textarea v-model="submitData.content" placeholder="请输入动态文字" count maxlength="500" border="none"
			auto-height></u-textarea>
		<view class="release_dynamics_img">
			<view v-for="(item,index) in imgs" :key="item"
				:style="{width:submitData.dynamicType === '1'?'auto':'30vw'}">
				<image :src="item" v-if="submitData.dynamicType === '0'" @click="handlePreview(index)"></image>
				<video :src="item" v-if="submitData.dynamicType === '1'" @click="handleVideoPreview(item)"
					:show-center-play-btn="false" :show-fullscreen-btn="false" :show-play-btn="false"
					:style="{height: Number(submitData.high)/5 + 'rpx',width:Number(submitData?.width)/5 +'rpx'}"></video>
				<text class="release_dynamics_img_del" @click="handleDel(index)">×</text>
			</view>
			<view class="release_dynamics_img_add"
				v-if="(submitData.dynamicType === '0' && imgs?.length < 9) || (submitData.dynamicType === '1' && imgs?.length < 1)"
				@click="handleSelect">
				<image src="http://qianxueapplet.suoeryun.com/imgAdd.png"></image>
			</view>
		</view>
		<view class="custom_form_body_item" @click="handleActivity()">
			<view class="custom_form_body_item_left">
				<image src="http://qianxueapplet.suoeryun.com/associatedActivities.png">
				</image>
				<text>选择关联活动</text>
			</view>
			<view class="custom_form_body_item_right">
				<text v-if="submitData?.activityName">{{submitData?.activityName}}</text>
				<!-- <text v-else class="placeholder">请选择</text> -->
				<u-icon name="arrow-right"></u-icon>
			</view>
		</view>
		<view class="custom_form_body_item">
			<view class="custom_form_body_item_left">
				<image src="http://qianxueapplet.suoeryun.com/look.png"></image>
				<text>谁可以看</text>
			</view>
			<view class="custom_form_body_item_right">
				<text>公开</text>
				<u-icon name="arrow-right"></u-icon>
			</view>
		</view>
		<!-- 撑满整屏 底部留的区域 -->
		<view style="height: 88rpx;"></view>
		<view class="release_dynamics_btm">
			<view class="safe_area">
				<button @click="handleRelease('0')">保存为草稿</button>
				<button @click="handleRelease('1')">发布</button>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { onLoad } from "@dcloudio/uni-app";
	import { ref, unref, reactive, toRaw, getCurrentInstance } from "vue";
	import { upload } from '@/config/sys.api';
	import { qxPlazaDynamicsAdd, qxPlazaDynamicsQueryById, qxPlazaDynamicsEdit } from '@/config/circle.api';

	const imgs = ref();
	const params = ref();
	const { proxy } = getCurrentInstance();
	const submitData = reactive({
		"activityId": "",
		"activityName": "",
		"addressCode": "",
		"city": "",
		"content": "",
		"county": "",
		"createBy": "",
		"createTime": "",
		"dynamicType": "",
		"id": "",
		"images": "",
		"plazaId": "",
		"province": "",
		"width": 0,//视频宽度
		"high": 0,//视频高度
	})

	onLoad(async (item) => {
		params.value = item;
		submitData.dynamicType = item?.type;
		const circleUrl = uni.getStorageSync('circle_url');
		console.log(item, 'sdf', circleUrl);
		if (item?.type === '1') {
			imgs.value = [circleUrl?.tempFilePath];
			submitData.width = circleUrl?.width;
			submitData.high = circleUrl?.height;
		} else {
			imgs.value = circleUrl?.split(',');
		}
		if (item?.id) {
			const res = await qxPlazaDynamicsQueryById({ id: item?.id });
			submitData.id = res?.id;
			submitData.activityName = res?.activityName;
			submitData.content = res?.content;
			submitData.dynamicType = res?.dynamicType;
			submitData.createBy = res?.createBy;
			imgs.value = res?.images?.split(',')
		}
	})

	/**
	 * 选择活动
	 */
	function handleActivity() {
		uni.navigateTo({
			url: "/pages/circle/selectActivity",
			success() {
				uni.$on('selectData', (item) => {
					console.log(item, 'selectData');
					submitData.activityId = item?.id;
					submitData.activityName = item?.activityName;
				})
			}
		})
	}

	/**
	 * 删除图片
	 */
	function handleDel(index) {
		imgs.value?.splice(index, 1);
	}

	/**
	 * 发布
	 */
	async function handleRelease(publishStatus) {
		const item = toRaw(submitData);
		if (item.content === '') {
			return uni.showToast({
				icon: 'none',
				title: '请输入动态文字'
			})
		}
		if (unref(imgs)?.length === 0) {
			return uni.showToast({
				icon: 'none',
				title: `请上传${unref(params?.type === '0' ? '图片' : '视频')}`
			})
		}
		let area = unref(proxy['vuex_current_position'])?.ad_info;
		let res;
		uni.showLoading();
		let data = unref(imgs)?.map(async item => {
			const result = await upload({ filePath: item, name: 'file', custom: { toast: false } });
			console.log(result, 'result');
			return result;
		})
		Promise.all(data).then(async (vals) => {
			if (item?.id) {
				res = await qxPlazaDynamicsEdit({
					...item,
					images: vals?.join(','),
					publishStatus,
					addressCode: area?.adcode,
					province: area?.province,
					city: area?.city,
					county: area?.district,
					latitude: area?.location?.lat,
					longitude: area?.location?.lng
				});
			} else {
				res = await qxPlazaDynamicsAdd({
					...item,
					images: vals?.join(','),
					publishStatus,
					addressCode: area?.adcode,
					province: area?.province,
					city: area?.city,
					county: area?.district,
					latitude: area?.location?.lat,
					longitude: area?.location?.lng
				});
			}
			uni.hideLoading();
			uni.showToast({
				icon: 'none',
				title: publishStatus === '0' ? '保存成功！' : '发布成功！',
				success() {
					if (item?.id) {
						uni.$emit('dynamicUpdate');
					}
					uni.$emit('circleUpdate');
					setTimeout(_ => {
						uni.removeStorageSync('circle_url');
						uni.navigateBack();
					}, 500)
				}
			});
		}).catch(err => {
			uni.hideLoading();
			// 失败时返回
			console.log(err)
		})
	}

	/**
	 * 选择图片
	 */
	function handleSelect() {
		const res = unref(params);
		console.log(res, 'res');
		if (res?.type == '0') {//图片
			uni.chooseMedia({
				count: 9 - unref(imgs)?.length,
				mediaType: ['image'],
				sourceType: ['album'],
				success: (d) => {
					imgs.value = d?.tempFiles?.map(item => item?.tempFilePath);
					// let data = d?.tempFiles?.map(async item => {
					// 	const result = await upload({ filePath: item?.tempFilePath, name: 'file', custom: { toast: false } });
					// 	return result;
					// })
					// Promise.all(data).then((vals) => {
					// 	uni.hideLoading();
					// 	imgs.value?.push(...vals);
					// }).catch(err => {
					// 	uni.hideLoading();
					// 	// 失败时返回
					// 	console.log(err)
					// })
				}
			})
		} else if (res?.type == '1') {//视频
			uni.chooseMedia({
				count: 1,
				mediaType: ['video'],
				sourceType: ['album'],
				success(d) {
					console.log(d, 'd');
					const item = d?.tempFiles[0];
					imgs.value = [item['tempFilePath']];
					submitData.width = item?.width;
					submitData.high = item?.height;
					// upload({ filePath: d?.tempFiles?.tempFilePath, name: 'file', custom: { toast: false } }).then(result => {
					// 	uni.hideLoading();
					// 	imgs.value?.push(result.message);
					// });
				}
			})
		}
	}

	/**
	 * 图片预览
	 */
	function handlePreview(index) {
		uni.previewImage({
			current: index,
			urls: unref(imgs),
		})
	}

	/**
	 * 视频预览
	 */
	async function handleVideoPreview(imgs) {
		uni.navigateTo({
			url: '/pages/circle/videoPreview?src=' + imgs,
		})
	}
</script>

<style lang="scss" scoped>
	.custom_form_body_item {

		// background-color: #fff;
		.custom_form_body_item_left {
			display: flex;
			align-items: center;

			image {
				width: 32rpx;
				height: 32rpx;
				margin-right: 20rpx;
			}

			font-size: 32rpx;

		}

		.custom_form_body_item_right {
			text {
				font-size: 28rpx;
				font-weight: 500;
			}
		}
	}

	::v-deep .u-textarea {
		background-color: transparent !important;
		padding-bottom: 30rpx !important;

		.u-textarea__count {
			background-color: transparent !important;
			color: #9AAFBC !important;
		}
	}

	.release_dynamics_img {
		padding-left: 26rpx;
		padding-bottom: 24rpx;
		padding-top: 20rpx;

		&>view {
			position: relative;
			margin-right: 10rpx;
			width: 30vw;
			display: inline-block;

			.release_dynamics_img_del {
				position: absolute;
				display: inline-block;
				background-color: #0e0e0e9c;
				color: #fff;
				font-size: 36rpx;
				font-weight: bolder;
				text-align: center;
				line-height: 36rpx;
				width: 36rpx;
				height: 36rpx;
				border-radius: 50%;
				top: 0;
				right: 0;
			}

			image,
			video {
				display: block;
				width: 30vw;
				height: 30vw;

			}
		}
	}

	.release_dynamics_btm {
		position: fixed;
		bottom: 0;
		width: calc(100vw - 26rpx - 26rpx);
		padding: 10rpx 26rpx;
		background-color: #fff;

		&>view {
			display: flex;
			justify-content: space-between;

			button {
				flex: 0.49;
				height: 68rpx;
				line-height: 68rpx;
				width: calc(100vw - 26rpx - 26rpx);
				font-size: 32rpx;
				margin: 0;
				padding: 0;
				border-radius: 54rpx;

				&:nth-child(1) {
					background-color: #fff;
					color: #FF943C;
					border: 2rpx solid #FF943C;
				}

				&:nth-child(2) {
					background-color: #FF943C;
					color: #fff;
				}

				&::after {
					border: 0;
				}
			}
		}
	}
</style>